<?php
namespace lib\users;

require_once('mysql.php');
require_once('ErrorCode.php');
use lib\mysql\Database;
use lib\errorcode\ErrorCode;


class users{
	private $db ;
	private $msg;
	public function __construct(){
		$this->db = new Database('localhost','root','168168','phpwamp');
		$this->db->select_table('users');
	}

	//登录
	public function login($user,$pwd){
		if(!empty($user) && !empty($pwd)){
			$data = array();
			$data['username'] = "'{$user}'";
			$data['pwd'] = "'{$this->_md5($pwd)}'";

			$rs = $this->db->where($data)->find();
			if($rs){
				return $arr = array('msg'=>'登录成功','code'=>ErrorCode::USERNAME_LOGIN_SUCCESS);
			}else{
				return $arr = array('msg'=>'登录失败','code'=>ErrorCode::USERNAME_LOGIN_FAILD);
			}

		}
	}
	//注册
	public function register($user,$pwd){
		$userInfo = array();
		if(!empty($user) && !empty($pwd)){
			if($this->_isUserExistes($user)){
				//用户名被注册
				return $arr = array('msg'=>'用户名已经存在','code'=>ErrorCode::USERNAME_EXISTS);
			};
			$userInfo['username'] = "'{$user}'";
			$userInfo['pwd'] = "'{$this->_md5($pwd)}'";
			$userInfo['ctime'] = time();
			$rs = $this->db->data($userInfo)->add();
			if($rs){
				return $arr = array('msg'=>'注册成功','code'=>ErrorCode::USERNAME_SUCCESS);
			}else{
				return $arr = array('msg'=>'注册失败','code'=>ErrorCode::USERNAME_FAILD);
			}



		}

	}
	//密码加密
	private function _md5($pwd,$key='test'){
		return md5($pwd.$key);
	}
	//检测用户名是否存在
	private function _isUserExistes($user){
		$exists = false;
		      $this->db->select_table('users');
		      $rs = $this->db->where(array('username'=>"'".$user."'"))->find();
		    
		if($rs){
			$exists = true;
		} 
		return $exists;
		
	}

}